package com.china08.yxyapi.util;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.china08.yxyapi.entity.db.res.YxyResBookContents;
import com.china08.yxyapi.entity.es.ElasticYxyResResource;
import com.china08.yxyapi.repository.db.YxyQuesKnowRepository;
import com.china08.yxyapi.repository.db.YxyResBookContentsRepository;

import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.MultimediaInfo;

@Component
public class YxyResUtil {

    @Value("${yxy.res.url}")
    private String yxy_res_url;

    @Value("${yx.rest.api.yx.path}")
    public String YX_API_PATH;

    public static final List<String> EXTENSION_FORMAT = new ArrayList<String>();

    static {
        EXTENSION_FORMAT.add("doc");
        EXTENSION_FORMAT.add("docx");
        EXTENSION_FORMAT.add("rtf");
        EXTENSION_FORMAT.add("xls");
        EXTENSION_FORMAT.add("xlsx");
        EXTENSION_FORMAT.add("et");
        EXTENSION_FORMAT.add("pptx");
        EXTENSION_FORMAT.add("ppt");
        EXTENSION_FORMAT.add("pdf");
        EXTENSION_FORMAT.add("rar");
        EXTENSION_FORMAT.add("zip");
        EXTENSION_FORMAT.add("7z");
        EXTENSION_FORMAT.add("wps");
        EXTENSION_FORMAT.add("txt");
    }

    /**
     * 获取资源预览地址
     * 
     * @param resId
     * @return
     */
    public String getPreviewUrl(String resId) {
        String previewUrl = yxy_res_url + "/res/browse/" + resId;
        return previewUrl;
    }

    /**
     * 获取资源下载地址
     * 
     * @param resId
     * @return
     */
    public String getDownloadUrl(String resId) {
        String string = System.currentTimeMillis() + "_";
        String string1 = DigestUtils.md5Hex("f0946d11126ef6852241bf811c534023" + resId);
        String AuthParam = string + string1;
        String downloadUrl = yxy_res_url + "/res/download/" + resId + "?AuthParam=" + AuthParam;
        return downloadUrl;
    }

    /**
     * 获取时长描述
     */
    public static String getDurationString(ElasticYxyResResource resResource) {
        Integer time = resResource.getDuration();
        long miao = time % 60; // 秒
        time = time / 60; // 转化为 分
        long shi = time / 60; // 转换为 时
        long fen = time % 60; // 转换为 分
        String duration = "";
        if (shi <= 0) {
            if (fen <= 0) {
                duration = miao + "秒";
            } else {
                duration = fen + "分" + miao + "秒";
            }
        } else {
            duration = shi + "时" + fen + "分" + miao + "秒";
        }
        return duration;
    }

    /**
     * 年+月+日 路径
     * 
     * @return
     */
    public static String getPath() {
        StringBuffer path = new StringBuffer("/");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        Date date = c.getTime();
        String pathDate = sdf.format(date);
        String year = pathDate.toString().substring(0, 4);
        path.append(year + "/");
        String mouth = pathDate.toString().substring(5, 7);
        path.append(mouth + "/");
        String day = pathDate.toString().substring(8, 10);
        path.append(day);
        String pathString = path.toString();
        return pathString;
    }

    /**
     * 年+月 路径
     * 
     * @return
     */
    public static String getPathMonth() {
        StringBuffer path = new StringBuffer("/");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM");
        Calendar c = Calendar.getInstance();
        Date date = c.getTime();
        path.append(sdf.format(date));
        return path.toString();
    }

    public Set<String> findTocByTocParent(List<String> parentTocId, Set<String> set) {
        YxyResBookContentsRepository bookContentsRepository = SpringContextUtil
                .getBean(YxyResBookContentsRepository.class);
        List<String> list = bookContentsRepository.findTocIdByParentTocId(parentTocId);
        if (list.size() > 0) {
            set.addAll(list);
            findTocByTocParent(list, set);
        }
        return set;
    }

    /**
     * 根据目录ID 获取这个目录底下的所有子目录
     * 
     * @param parentTocId
     * @return
     */
    public List<String> findTocByTocParent(String parentTocId) {
        Set<String> childIds = new HashSet<String>();
        childIds.add(parentTocId);
        Set<String> set = findTocByTocParent(Arrays.asList(new String[] { parentTocId }), childIds);
        List<String> list = new ArrayList<String>();
        list.addAll(set);
        return list;
    }

    /**
     * 根据知识点ID 获取这个知识点底下的所有子知识点
     * 
     * @param parentTocId
     * @return
     */
    public List<Integer> findTocByTocKnowParent(Integer parentTocId) {
        Set<Integer> childIds = new HashSet<Integer>();
        childIds.add(parentTocId);
        Set<Integer> set = findTocByTocKnowParent(Arrays.asList(new Integer[] { parentTocId }), childIds);
        List<Integer> list = new ArrayList<Integer>();
        list.addAll(set);
        return list;
    }

    public Set<Integer> findTocByTocKnowParent(List<Integer> parentTocId, Set<Integer> set) {
        YxyQuesKnowRepository yxyQuesKnowRepository = SpringContextUtil.getBean(YxyQuesKnowRepository.class);
        List<Integer> list = yxyQuesKnowRepository.findTocIdByParentTocId(parentTocId);
        if (list.size() > 0) {
            set.addAll(list);
            findTocByTocKnowParent(list, set);
        }
        return set;
    }

    public Set<String> findTocParentBychildId(String id, Set<String> set) {
        YxyResBookContentsRepository bookContentsRepository = SpringContextUtil
                .getBean(YxyResBookContentsRepository.class);
        YxyResBookContents bookContents = bookContentsRepository.findById(id);
        if (bookContents != null) {
            set.add(bookContents.getId());
            if (!StringUtils.equals(bookContents.getpId(), "0")) {
                findTocParentBychildId(bookContents.getpId(), set);
            }
        }
        return set;
    }

    /***
     * 获得这个目录的所有父节点
     * 
     * @param parentTocId
     * @return
     */
    public List<String> findTocParentByTocId(String id) {
        Set<String> set = new HashSet<String>();
        set.add(id);
        Set<String> tocSet = findTocParentBychildId(id, set);
        List<String> tocList = new ArrayList<String>();
        tocList.addAll(tocSet);
        return tocList;
    }

    /**
     * 所有资源id的自增, 资源id生产采用
     * 
     * @param nowId
     * @return
     */
    public static String createResId(String nowId) {

        if (StringUtils.isBlank(nowId)) { return ""; }
        if (!nowId.startsWith("yx")) { return ""; }
        if (nowId.length() != 6) { return ""; }
        if (!StringUtils.isNumeric(nowId.substring(2))) { return ""; }

        return "yx" + StringUtils.leftPad(Integer.parseInt(nowId.substring(2)) + 1 + "", 4, "0");
    }

    public static YxyResBookContents findRoot(String bookcontent) {
        YxyResBookContentsRepository bookContentsRepository = SpringContextUtil
                .getBean(YxyResBookContentsRepository.class);
        YxyResBookContents bookContents = bookContentsRepository.findById(bookcontent);
        if (bookContents != null && !StringUtils.equals(bookContents.getpId(), "0")) {
            findRoot(bookContents.getpId());
        }
        return bookContents;
    }

    /**
     * 获取时长转换描述
     */
    public static String getDurationToString(Integer time) {
        long miao = time % 60; // 秒
        time = time / 60; // 转化为 分
        long shi = time / 60; // 转换为 时
        long fen = time % 60; // 转换为 分
        String duration = "";
        if (shi <= 0) {
            if (fen <= 0) {
                duration = miao + "秒";
            } else {
                duration = fen + "分" + miao + "秒";
            }
        } else {
            duration = shi + "时" + fen + "分" + miao + "秒";
        }
        return duration;
    }

    /**
     * 获取时长
     * 
     */
    public static long getDuration(String path) throws Exception {
        File source = new File(path);
        if (source.exists()) {
            Encoder encoder = new Encoder();
            MultimediaInfo multimediaInfo = encoder.getInfo(source);
            long ls = multimediaInfo.getDuration();
            // LOGGER.info("此视频时长为:::::::::::" + ls);
            return ls;
        }
        return 0l;
    }
}
